package day8;

import java.util.HashMap;

class LRUCache {

    class Dnode{
        int key;
        int value;
        Dnode prev ;
        Dnode next;

        Dnode(){}
        Dnode(int key,int value){
            this.key = key;
            this.value = value;
        }

    }
    HashMap<Integer,Dnode> map = new HashMap<>();
    Dnode head,tail;
    int capacity;
    int size ;


    public LRUCache(int capacity) {
        this.size=0;
        this.capacity = capacity;
        this.head = new Dnode();
        this.tail = new Dnode();
        head.next = tail;
        tail.prev = head;
    }

    public int get(int key) {
        Dnode node = map.get(key);
        if(node==null) return -1;
        moveNode(node);
        return node.value;
    }

    public void put(int key, int value) {
        Dnode node = map.get(key);
        if(node==null){
            Dnode n = new Dnode(key,value);
            map.put(key, n);
            addHead(n);
            size++;
            if(size>capacity){
                map.remove(tail.prev.key);
                delTail();
                size--;
            }
        }else {
            node.value = value;
            moveNode(node);
        }
    }

    public void delNode(Dnode node){
        Dnode x = node.prev;
        Dnode y = node.next;
        x.next = y;
        y.prev = x;
    }

    public void addHead(Dnode node){
        node.prev = head;
        node.next = head.next;
        head.next.prev = node;
        head.next = node;
    }
    public void moveNode(Dnode node){
        delNode(node);
        node.prev = head;
        node.next = head.next;
        head.next.prev = node;
        head.next = node;
    }

    public void delTail(){
        delNode(tail.prev);
    }
}

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */
